package org.jvending.provisioning.adapter;

import javax.provisioning.adapter.Adapter;
import javax.provisioning.adapter.AdapterException;
import javax.provisioning.adapter.AdapterContext;
import javax.provisioning.DescriptorFile;
import javax.provisioning.FulfillmentTask;
import javax.provisioning.BundleDescriptor;
import java.net.URL;

public class MavenAdapter extends Adapter {

    public DescriptorFile createDescriptorFile(URL url) throws AdapterException {
        if (url == null) throw new AdapterException("JV-1200-001: MIDP", "URL can not be null");
        AdapterContext adapterContext = adapterConfig.getAdapterContext();
        //sanity check
        if (adapterContext == null)
            throw new AdapterException("MVND", "JV-1200-002: SEVERE exception: AdapterContext is null");

        //spec (7.3.2.1): must pass to delivery component
        String fulfillmentId = null;
        String query = url.getQuery();
        if (query == null)
            throw new AdapterException("MVND", "JV-1200-008: The URL is missing the fid parameter: URL = "
                    + url.toString());

        String[] queryTokens = query.split("[&]");
        for (int i = 0; i < queryTokens.length; i++) {
            String token = queryTokens[i];
            if (token.startsWith("fid")) {
                String[] ids = token.split("=");
                fulfillmentId = ids[1];
            }
        }

        FulfillmentTask fulfillmentTask = adapterContext.getFulfillmentTask(fulfillmentId, null, "mvnd");
        BundleDescriptor bundleDescriptor = fulfillmentTask.getBundleDescriptor();

        if (bundleDescriptor == null)
            throw new AdapterException("MVND", "JV-1200-003: Could not locate the BundleDescriptor: FulfillmentID = "
                    + fulfillmentId);

        //Get the descriptorFile (JAD) they we are going to modify with new properties
        DescriptorFile descriptorFile = (DescriptorFile) bundleDescriptor.getDescriptorFile();
        if (descriptorFile == null)
            throw new AdapterException("MVND", "JV-1200-004: Could not locate the DescriptorFile: FulfillmentID = "
                    + fulfillmentId);
        return descriptorFile;
    }

    public String createFulfillmentURI(FulfillmentTask fulfillmentTask) throws AdapterException {
        if (fulfillmentTask == null) throw new AdapterException("MIDP", "JV-1200-007: FulfillmentTask is null");
        if (adapterConfig == null) {
            System.out.println("AdapterConfig is null");
        }
        System.out.println("Base URI = " + adapterConfig.getBaseURI());
        if (adapterConfig.getAdapterContext() == null) {
            System.out.println("AdapterContext is null");
        }
        return adapterConfig.getAdapterContext().getServletContext().getInitParameter("CONTENT_DELIVERY_URI")
                + adapterConfig.getBaseURI() + "?fid=" + fulfillmentTask.getFulfillmentID();
    }
}
